package com.lj.back.manage.scaffold.module.sys.shiro;

import com.lj.back.manage.scaffold.common.enums.ResponseEnum;
import com.lj.back.manage.scaffold.common.util.Assert;
import com.lj.back.manage.scaffold.module.sys.DTO.SysUserDTO;
import com.lj.back.manage.scaffold.module.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 后台管理Realm
 * @author lv
 * @version 1.0.0
 */
@Component
@Slf4j
@AllArgsConstructor
public class SysRealm extends AuthorizingRealm {

    /**
     * 延迟加载  避免shiro在spring之前初始化bean  导致spring部分功能失效
     */
    @Lazy
    private final SysUserService sysUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof BearerToken;
    }


    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        Assert.assertNotNull(primaryPrincipal, ResponseEnum.TOKEN_INVALID);
        SysUserDTO user = (SysUserDTO) primaryPrincipal;
        Set<String>  permsSet = sysUserService.listUserPermissions(user.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        BearerToken bearerToken = (BearerToken) token;
        SysUserDTO user = sysUserService.getUserByToken(bearerToken.getToken());
        Assert.assertNotNull(user, ResponseEnum.TOKEN_INVALID);
        return new SimpleAuthenticationInfo(user, bearerToken.getToken(), getName());
    }
}
